<?php

namespace Trois\Lib;

class PassTool
{

    private static string $key = "deux.trois";

    /**
     * 加密
     */
    public static function encrypt(string $txt): string
    {
        srand((double)microtime() * 1000000);
        $encrypt_key = md5(rand(0, 32000));
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($txt); $i++) {
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            $tmp .= $encrypt_key[$ctr] . ($txt[$i] ^ $encrypt_key[$ctr++]);
        }
        return urlencode(base64_encode(self::handle($tmp)));
    }

    /**
     * 解密
     */
    public static function decrypt(string $txt): string
    {
        $txt = self::handle(base64_decode(urldecode($txt)));
        $tmp = '';
        for ($i = 0; $i < strlen($txt); $i++) {
            $md5 = $txt[$i];
            $tmp .= $txt[++$i] ^ $md5;
        }
        return $tmp;
    }

    /**
     *
     * @param $txt
     * @return string
     */
    private static function handle($txt): string
    {
        $encrypt_key = md5(self::$key);
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($txt); $i++) {
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
        }
        return $tmp;
    }

}